package day12;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

/**
 * 使用DOM生产xml文档
 * @author Administrator
 *
 */
public class WriteXmlDemo {

	public static void main(String[] args) {
		List<Emp> empList = new ArrayList<Emp>();
		empList.add(new Emp(1,"张三",22,"男",3000));
		empList.add(new Emp(2,"张四",23,"女",4000));
		empList.add(new Emp(3,"张五",24,"男",5000));
		empList.add(new Emp(4,"张六",25,"女",6000));
		empList.add(new Emp(5,"张七",26,"男",7000));
		
		/*
		 * 将empList集合中的员工信息存到myemp.xml中
		 * 
		 * 写出XML文档的步骤:
		 * 1.创建一个Document对象表示一个空白xml
		 * 2.向Document对象中添加根元素
		 * 3.按照应当生成的xml文档的格式逐级向根元素中添加子元素以形成xml文档格式
		 * 4.创建XmlWriter
		 * 5.通过XmlWriter将Document写出
		 * */
		XMLWriter xw = null;
		try {
			//1
			Document document = DocumentHelper.createDocument();
			//2添加根标签<list>
			Element root = document.addElement("list");
			for(Emp emp:empList) {
				/*
				 * Element addElement(String name)
				 * 向当前标签中添加给定名字的子标签并将其返回
				 * 
				 * Element addText(String text)
				 * 向当前标签中添加文本信息，返回值为当前标签
				 * 
				 * Element addAttribute(String name,String value)
				 * 向当前标签中添加属性，返回值为当前标签
				 * */
				root.addAttribute("id", String.valueOf(emp.getId()));
				Element empEle = root.addElement("emp");
				empEle.addElement("name").addText(emp.getName());
				empEle.addElement("age").addText(emp.getAge() + "");
				empEle.addElement("gender").addText(emp.getGender());
				empEle.addElement("salary").addText(String.valueOf(emp.getSalary()));
				
			}
			FileOutputStream fos = new FileOutputStream("myemp.xml");
			//格式化输出
			xw = new XMLWriter(fos,OutputFormat.createPrettyPrint());
			xw.write(document);
			System.out.println("写出完毕");
			
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			if(xw != null) {
				try {
					xw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
